package inits

import (
	"fmt"
	"github.com/go-redis/redis"
	"go-jwt-auth/basic/config"
	"go-jwt-auth/basic/global"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
)

func Inits() {
	config.GetViperData()
	MysqlInit()
	RedisInit()
}
func MysqlInit() {
	var err error
	data := config.AppViperData.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", data.User, data.Password, data.Host, data.Port, data.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	} else {
		log.Println("mysql init success")
	}
}
func RedisInit() {
	global.RDB = redis.NewClient(&redis.Options{
		Addr:     config.AppViperData.Redis.Addr,
		Password: config.AppViperData.Redis.Password,
		DB:       config.AppViperData.Redis.DB,
	})
	err := global.RDB.Ping().Err()
	if err != nil {
		panic(err)
	} else {
		log.Println("redis init success")
	}
}
